package org.csu.mypetstore.controller;

import org.csu.mypetstore.domain.Account;
import org.csu.mypetstore.service.CatalogService;
import org.csu.mypetstore.domain.CartItem;
import org.csu.mypetstore.domain.Cart;
import org.csu.mypetstore.domain.Item;
import org.csu.mypetstore.service.CartService;
import org.csu.mypetstore.service.ItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpSession;
import jakarta.servlet.http.HttpServletResponse;
import java.util.List;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import org.csu.mypetstore.vo.ItemVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.Map;
import org.springframework.web.bind.annotation.ResponseBody;


@Controller
@RequestMapping("/catalog")
public class CartController {

    @Autowired
    private CartService cartService;
    @Autowired
    private CatalogService catalogService;
    @Autowired
    private ItemService itemService;



    @GetMapping("viewCart")
    public String viewCart(HttpSession session, Model model) {
        Account account = (Account) session.getAttribute("loginAccount");
        if (account == null) {
            return "account/SignonForm";
        }

        // 如果会话中没有购物车，创建新实例
        Cart cart = (Cart) session.getAttribute("cart");
        if (cart == null) {
            cart = new Cart();
            session.setAttribute("cart", cart);
        }

        // 将会话中的购物车传递给视图
        model.addAttribute("cart", cart);
        return "cart/cart";
    }


    @GetMapping("/addItemToCart")
    public String addToCart(
            @RequestParam("itemId") String itemId,
            HttpSession session,
            Model model
    ) {
        Account account = (Account) session.getAttribute("loginAccount");
        if (account == null) {
            model.addAttribute("error", "您还没登录，请先登录");
            return "account/SignonForm";
        }

        // 确保购物车存在
        Cart cart = (Cart) session.getAttribute("cart");
        if (cart == null) {
            cart = new Cart();
            session.setAttribute("cart", cart);
        }

        // 添加商品逻辑
        if (itemId != null) {
            if (cart.containsItemId(itemId)) {
                cart.incrementQuantityByItemId(itemId);
            } else {
                Item item = itemService.getItemById(itemId);
                boolean isInStock = true; // 假设默认有库存
                cart.addItem(item, isInStock);
            }
        }

        // 更新会话中的购物车
        session.setAttribute("cart", cart);
        model.addAttribute("cart", cart);
        return "cart/cart";
    }

    @GetMapping("/remove")
    public String removeFromCart(@RequestParam("itemId") String itemId,
                                 HttpSession session, Model model) {


        Cart cart = (Cart) session.getAttribute("cart");
        if (cart != null) {
            // 仅移除指定商品
            cart.removeItemById(itemId);
            // 更新session中的购物车
            session.setAttribute("cart", cart);

            // 将更新后的购物车返回给视图
            model.addAttribute("cart", cart);
        }
        return "cart/cart";
    }

    @PostMapping("/updateCartItem")
    @ResponseBody
    public Map<String, Object> updateCartItem(
            @RequestParam String itemId,
            @RequestParam int quantity,
            HttpSession session) {

        Map<String, Object> result = new HashMap<>();
        Account account = (Account) session.getAttribute("loginAccount");
        if (account == null) {
            result.put("status", "error");
            result.put("message", "未登录");
            return result;
        }

        Cart cart = (Cart) session.getAttribute("cart");
        if (cart != null) {
            cart.setQuantityByItemId(itemId, quantity); // 需要Cart类实现这个方法
            session.setAttribute("cart", cart);

            // 可选：持久化到数据库
            cartService.updateCartItem(account.getUsername(), itemId, quantity);

            result.put("status", "success");
        } else {
            result.put("status", "error");
            result.put("message", "购物车不存在");
        }
        return result;
    }
}

